package edu.mama.college.aspect;

import edu.mama.college.model.User;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 前端资源请求过滤器
 * 注意：WebFilter、WebServlet等注解不是Spring的注解，默认不生效，需要在SpringBoot的启动程序类上添加注解 @ServletComponentScan 启用
 */
@WebFilter(urlPatterns = "*.html")
public class PageAccessFilter extends HttpFilter {

    /**
     * 每一次请求时都只调用方法doFilter()进行处理；
     * @param request
     * @param response
     * @param chain 过滤链。Web项目可以配置多个Filter，一个HTTP请求要经过所有匹配的过滤器后，才会交由匹配的Servlet去处理。
     */
    @Override
    protected void doFilter(HttpServletRequest request,
                            HttpServletResponse response,
                            FilterChain chain) throws IOException, ServletException {

        //TODO 拦截 /user/*.html 和 /admin/*.html
        if(!request.getRequestURI().startsWith("/user/") && !request.getRequestURI().startsWith("/admin/")){
            super.doFilter(request, response, chain);
            return;
        }

        User user = (User) request.getSession().getAttribute("user");
        if(user == null){
            response.sendRedirect("/login.html");
            return;
        }

        if(request.getRequestURI().startsWith("/admin/")){
            if(!"ADMIN".equals(user.getRole())){
                response.sendRedirect("/login.html");
                return;
            }
        }

        //不拦截的HTTP请求，交由下一个过滤器去处理
        super.doFilter(request, response, chain);
    }
}
